﻿using Microsoft.Extensions.Options;
using System.Net;
using System.Net.Mail;

namespace Away.Common.Notify.Email;

public class EmailSettings
{
    public required string Host { get; set; }
    public required string Account { get; set; }
    public required string Password { get; set; }
}

public class EmailNotifyService : IEmailNotifyService
{
    private readonly ILogger<EmailNotifyService> _logger;
    private SmtpClient? _client;
    private readonly EmailSettings _emailSettings;

    public EmailNotifyService(IOptionsMonitor<EmailSettings> options, ILogger<EmailNotifyService> logger)
    {
        _emailSettings = options.CurrentValue;
        _logger = logger;
    }

    public SmtpClient Client
    {
        get
        {
            if (_client != null)
            {
                return _client;
            }

            _client = new()
            {
                DeliveryMethod = SmtpDeliveryMethod.Network,
                Host = _emailSettings.Host,
                EnableSsl = true,
                UseDefaultCredentials = false,
                Credentials = new NetworkCredential(_emailSettings.Account, _emailSettings.Password)
            };
            return _client;
        }
    }

    public bool Send(string target, string title, string content)
    {
        return Send(target, o =>
        {
            o.Subject = title;
            o.Body = content;
        });
    }

    public bool Send(string target, Action<MailMessage> action)
    {
        try
        {
            MailMessage message = new(_emailSettings.Account, target)
            {
                BodyEncoding = Encoding.UTF8,
                IsBodyHtml = false,
                Priority = MailPriority.Normal
            };
            action(message);
            Client.Send(message);
            return true;
        }
        catch (Exception ex)
        {
            _logger.LogWarning(ex, "send email error");
            return false;
        }
    }
}
